from django.shortcuts import render, redirect
from .forms import SignUpForm
from django.contrib.auth import login, authenticate
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt


def index_view(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('home')  # Assume we have a home view to redirect to
    else:
        form = SignUpForm()
    return render(request, 'accounts/index.html', {'form': form})


@csrf_exempt
def register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        email = request.POST.get('email')
        password = request.POST.get('password')
        if not (username and email and password):
            return JsonResponse({'error': '缺少必要的字段'}, status=400)
        if User.objects.filter(username=username).exists():
            return JsonResponse({'error': '用户名已存在'}, status=400)
        user = User.objects.create_user(username=username, email=email, password=password)
        return JsonResponse({'message': '用户创建成功'}, status=201)
    return JsonResponse({'error': '需要POST请求'}, status=400)


@csrf_exempt
def login_view(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        print(username, password)
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return JsonResponse({'message': '登录成功'}, status=200)
        else:
            return JsonResponse({'error': '无效的用户名或密码'}, status=400)
    return JsonResponse({'error': '需要POST请求'}, status=400)
